<template>
  <div class="new-page assessmentRecord">
    <!-- 查询 -->
    <div class="search margin-bot">
      <a-input-search
        placeholder="请输入考核名称查询"
        style="width: 100%"
        @search="onSearch"
        v-model="likeName"
      />
    </div>
    <div class="margin-bot" style="margin-bottom:20px">
      <a-button type="primary" icon="plus" @click="showModal">新增</a-button>
    </div>
    <!-- 表格 -->
    <div class="margin-bot">
      <a-table :columns="columns" :data-source="data" :defaultExpandedRowKeys='firstKey'>
        <span slot="action" slot-scope="text, record">
          <a style="margin-right:30px;color:#1890FF" @click="onEdit(text, record)">编辑</a>
          <a-popconfirm
            title="是否确认删除"
            ok-text="确认"
            cancel-text="取消"
            @confirm="confirm(text)"
            @cancel="cancel"
          >
            <a style="color:#1890FF">删除</a>
          </a-popconfirm>
        </span>
        <span slot="remark" slot-scope="text">
          <a-tooltip placement="top">
            <template slot="title">
              <span>{{text}}</span>
            </template>
            <div class="remarks">{{text}}</div>
          </a-tooltip>
        </span>
        <div
          slot="expandedRowRender"
          slot-scope="record"
          v-if="record.description.data!=null"
          style="margin: 0;"
        >
          <div class="flexStart">
            <div class="flexCenter">
              <div class="openTabDiv">考核资料：</div>
              <div class="openTabDiv">
                <div v-for="(item,index) in record.description.data" :key="index" @click="showPdf(item.fileUrl)">
                  <span class="checkInfo">{{item.fileName}}</span>
                </div>
              </div>
            </div>
            <!-- <div>创建人：{{record.description.people}}</div> -->
            <!-- <div>创建人：{{record.description.updata}}</div> -->
          </div>
        </div>
      </a-table>
    </div>
    <!-- 分页 -->
    <div class="pagination flexBetween">
      <div>共{{total}} 条记录 第 {{current}} / {{Math.ceil((total/pageSize))}} 页</div>
      <div>
        <a-pagination
          :current="current"
          :page-size-options="pageSizeOptions"
          :total="total"
          show-size-changer
          :page-size="pageSize"
          @change="pageChange"
          @showSizeChange="onShowSizeChange"
          show-quick-jumper
        >
          <template slot="buildOptionText" slot-scope="props">
            <span v-if="props.value !== '40'">{{ props.value }}条/页</span>
            <span v-if="props.value === '40'">全部</span>
          </template>
        </a-pagination>
      </div>
    </div>
    <!-- 对话框 -->
    <a-modal
      v-model="visible"
      :title="modalTitle"
      @ok="handleOk"
      :maskClosable="false"
      cancelText="取消"
      okText="确认"
    >
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        v-if="visible"
      >
        <a-form-model-item ref="name" label="考核名称" prop="name">
          <a-input
            v-model="form.name"
            :maxLength="30"
            @blur="
          () => {
            $refs.name.onFieldBlur();
          }
        "
          />
        </a-form-model-item>

        <a-form-model-item ref="judgeObject" label="考核对象" prop="judgeObject">
          <a-input
            v-model="form.judgeObject"
            :maxLength="30"
            @blur="
          () => {
            $refs.judgeObject.onFieldBlur();
          }
        "
          />
        </a-form-model-item>

        <a-form-model-item ref="result" label="考核结果" prop="result">
          <a-input
            v-model="form.result"
            :maxLength="30"
            @blur="
          () => {
            $refs.result.onFieldBlur();
          }
        "
          />
        </a-form-model-item>

        <a-form-model-item label="考核日期" required prop="judgeDate">
          <a-date-picker
            v-model="form.judgeDate"
            type="date"
            placeholder="请选择日期"
            style="width: 100%;"
          />
        </a-form-model-item>

        <a-form-model-item label="备注说明">
          <a-input v-model="form.remark" type="textarea" :auto-size="{ minRows: 3, maxRows: 5 }" />
        </a-form-model-item>

        <a-form-model-item label="考核资料" prop="formUpload">
          <a-upload
            name="file"
            accept=".pdf"
            :multiple="true"
            :remove="handleRemove"
            :before-upload="beforeUpload"
            :default-file-list="defaultFileList"
          >
            <a-button>
              <a-icon type="upload" />上传文件
            </a-button>
            <div style="color:#ccc">请上传pdf文件</div>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- pdf对话框 -->
    <div>
      <a-modal
        v-model="visible2"
        title
        @ok="handleOk2"
        :footer="null"
        :maskClosable="false"
        width="1080px"
        :bodyStyle="{textAlign:'center'}"
        v-if="visible2"
        key="modal2"
        class="pdfModal"
      >
        <embed
          width="1000"
          height="700"
          :src="this.pdfUrl"
          type
        />
      </a-modal>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { judgeAdd, judgeQuery, judgeGet, judgeUpdate, judgeDelete } from '@/api/judge.js'
import { uploadOSS } from '@/utils/oss.js'
import { message } from 'ant-design-vue'
export default {
  data() {
    let formUpload = (rule, value, callback) => {
      if (this.pdfData === false) {
        callback(new Error('请上传文件'))
      } else {
        this.$refs.ruleForm.validateField('formUpload')
        callback()
      }
    }
    return {
      columns: [
        { title: '考核名称', dataIndex: 'name', key: 'name' },
        { title: '考核对象', dataIndex: 'judgeObject', key: 'judgeObject' },
        { title: '考核结果', dataIndex: 'result', key: 'result' },
        { title: '考核日期', dataIndex: 'judgeDate', key: 'judgeDate' },
        { title: '备注', dataIndex: 'remark', key: 'remark', scopedSlots: { customRender: 'remark' } },

        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      data: [],
      pageSizeOptions: ['5', '10', '20', '30', '40'],
      current: 1,
      pageSize: 10,
      likeName: '',
      total: 50,
      modalTitle: '新增考核记录',
      visible: false,
      visible2: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form: {
        name: '',
        judgeObject: '',
        packageId: '',
        result: '',
        remark: '',
        judgeDate: moment(new Date()),
        fileInfoList: [],
        id: ''
      },
      defaultFileList: [],
      firstKey:[],
      rules: {
        name: [
          {
            required: true,
            message: '请输入考核名称',
            trigger: 'change'
          }
        ],
        judgeObject: [
          {
            required: true,
            message: '请输入考核对象',
            trigger: 'change'
          }
        ],
        result: [
          {
            required: true,
            message: '请输入考核结果',
            trigger: 'change'
          }
        ],
        judgeDate: [{ required: true, message: '请选择考核时间', trigger: 'change' }],
        formUpload: [{ required: true, validator: formUpload, trigger: 'change' }]
      },
      headers: {
        authorization: 'authorization-text'
      },
      pdfData: false,
      flag: false,
      pdfUrl:''
    }
  },
  mounted() {
    this.getTable()
  },
  methods: {
    moment,
    getTable() {
      let data1 = {}
      data1.likeName = this.likeName
      data1.page = this.current
      data1.size = this.pageSize
      let _this = this
      judgeQuery(data1).then((res) => {
        let tabdata = res.data.data
        _this.data = []
        tabdata.forEach((item, index) => {
          item.key = item.id
          item.judgeDate = moment(item.judgeDate).format('YYYY-MM-DD')
          item['description'] = {}
          item['description']['data'] = item.fileList
          item['description']['people'] = item.updateId
          item['description']['judgeDate'] = item.judgeDate
        })
        _this.data = tabdata
        this.firstKey[0]=tabdata[0].key
        this.total = res.data.total
        // console.log(_this.data)
      })
    },
    onEdit(text) {
      this.modalTitle = '编辑考核记录'
      // console.log(text)

      this.form.packageId = ''
      this.form.fileInfoList = []
      this.defaultFileList = []
      this.form.name = ''
      this.form.judgeDate = ''

      this.form.name = text.name
      this.form.judgeDate = moment(new Date(text.judgeDate))
     
      this.form.id = text.id
      this.form.remark = text.remark
      this.form.judgeObject = text.judgeObject
      this.form.result = text.result
      this.form.packageId = text.packageId
      text.fileList.forEach((item, index) => {
        let fileObj = {}
        fileObj['uid'] = index
        fileObj['status'] = 'done'
        fileObj['url'] = item.fileUrl
        fileObj['name'] = item.fileName
        this.form.fileInfoList.push(fileObj)
        this.defaultFileList.push(fileObj)
      })
      if (this.defaultFileList.length != 0) this.pdfData = true
      this.visible = true
    },
    onDelete(text) {
      let data = {}
      data.id = text.id
      judgeDelete(data).then((res) => {
        message.destroy()
        this.$message.success('删除成功')
        this.getTable()
        // console.log(res)
      })
    },
    confirm(item) {
      // console.log(e);
      this.onDelete(item)
    },
    cancel(e) {
      // console.log(e);
      this.$message.error('取消删除')
    },
    onSearch(value) {
      // this.likeName = value
      this.current=1
      this.getTable()
    },
    onShowSizeChange(current, pageSize) {
      // console.log(current, pageSize)
      this.current = 1
      this.pageSize = pageSize

      this.getTable()
    },
    pageChange(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.getTable()
    },
    showModal() {
      this.form.packageId = ''
      this.form.result = ''
      this.form.remark = ''
      this.form.fileInfoList = []
      this.defaultFileList = []
      this.form.name = ''
      this.form.judgeObject = ''
      this.form.judgeDate = moment(new Date())
      this.modalTitle = '新增考核记录'
      this.flag = true
      this.visible = true
    },
    showPdf(text) {
      this.pdfUrl=text
      this.visible2 = true
    },
    handleOk2() {
      this.visible2 = false
    },
    handleOk(e) {
      this.form.name=this.form.name.trim()
      this.form.judgeObject=this.form.judgeObject.trim()
      this.form.result=this.form.result.trim()
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let data = {}
          data['fileInfoList'] = []
          this.form.fileInfoList.forEach((item, index) => {
            let obj = { fileName: '', fileUrl: '' }
            obj.fileName = item.name
            obj.fileUrl = item.url
            data['fileInfoList'].push(obj)
          })
          data.name = this.form.name
          data.judgeDate = this.form.judgeDate
          data.judgeObject = this.form.judgeObject
          data.id = this.form.id
          
          data.packageId = this.form.packageId
          data.remark = this.form.remark
          data.result = this.form.result
          if (this.modalTitle != '编辑考核记录') {
            judgeAdd(data).then((res) => {
              console.log(res)
              this.$message.success('新增成功')
              this.getTable()
            })
          } else {
            judgeUpdate(data).then((res) => {
              console.log(res)
              this.$message.success('编辑成功')
              this.getTable()
            })
          }
          this.visible = false
        } else {
          // console.log('error submit!!');
          return false
        }
      })
    },
    handleRemove(file) {
      console.log(file.uid)
      this.form.fileInfoList.forEach((item, index) => {
        if (file.uid == item.uid) {
          this.form.fileInfoList.splice(index, 1)
        }
      })
      if (this.form.fileInfoList.length != 0) {
        this.pdfData = true
      } else {
        this.pdfData = false
      }
      // this.form.fileInfoList
    },

    beforeUpload(file) {
      // console.log(file)
      const reader = new FileReader()
      reader.readAsDataURL(file) // 读取图片文件
      if (this.modalTitle != '编辑考核记录' && this.flag == true) {
        this.form.packageId = file.uid
        this.flag = false
      }
      reader.onload = (data) => {
        //  console.log(file)
        this.uploadFile(data.target.result, file.name, file.uid, this.form.packageId)
      }
      this.pdfData = true

      this.$message.success(`${file.name} 上传成功`, 1)
      return false
    },
    uploadFile(base64Data, fileName, fileUid, packageId) {
      let blob = this.dataURLtoBlob(base64Data)
      // console.log(fileUid);

      let dir = 'lw/' + 'JU' + packageId + '/'
      uploadOSS(blob, fileName, dir).then((fileUrl) => {
        // console.log(fileUrl, fileName)
        let obj = { url: fileUrl, name: fileName, uid: fileUid }
        // console.log( obj.fileUid );
        this.form.fileInfoList.push(obj)
      })
    },
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], {
        type: mime
      })
    }
  }
}
</script>

<style scoped lang="less">
.search {
  padding-top: 30px;
  display: flex;
  justify-content: flex-end;
}
.assessmentRecord {
  background: #fff;
  padding: 15px 30px;
}
.margin-bot {
  margin-bottom: 30px;
}

.checkInfo:hover {
  color: #1890ff;
  cursor: pointer;
}
.tdShow {
  display: none;
}
.remarks {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  width: 85px;
}
.pdfModal {
  ::v-deep .ant-modal {
    width: 1080px !important;
    top: 20px;
  }
}
.pdfModal ::v-deep .ant-modal-body {
  padding: 40px;
  text-align: center;
  height: 780px;
}
</style>
